package cn.gq.sssm.shiro;

import cn.gq.sssm.pojo.User;
import com.sun.xml.internal.messaging.saaj.packaging.mime.util.LineInputStream;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ASUS
 * @date 2020/5/7
 */
public class CustomRealm extends AuthorizingRealm {


    //模拟从数据库查询数据
    private List<String> users = Arrays.asList("lucy", "wukong", "alex");
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //获取主身份
        User user= (User) principalCollection.getPrimaryPrincipal();

        //分配权限
        List<String> permission=new ArrayList<String>();
        //permission.add("user:list");
        permission.add("department:list");
        permission.add("role:list");

        System.out.println("当前拥有的权限"+permission);
        //创建授权信息对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //添加角色名称给授权信息对象
        info.addRole("hr");

        info.addStringPermissions(permission);
        return info;
    }



    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //获取token账号密码
        String username = (String) authenticationToken.getPrincipal();


        System.out.println(username);
        if (!users.contains(username)) {
            System.out.println("111");
            //不存在数据
            return null;
        }

        //如果存在则获取对象
        User user = new User(username, "142a04d176b6960cf517c6b2bac95630", "qwer");

        Object principal = user;

        Object credentials = user.getPassword();

        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, this.getName());
        return authenticationInfo;


    }
}
